package x7.heatctrl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;

public class TimeZone {
	
	String[] tokens;
	Calendar c = new GregorianCalendar();
	static DateFormat weekday = new SimpleDateFormat("-MMM-EEE-",Locale.ENGLISH);


	private String prefix;
	public TimeZone(String prefix, String def) {
		tokens = def==null?new String[0]:def.split("&");
		this.prefix=prefix;
	}
	
	public boolean fits(Date current) {
		if (tokens==null || tokens.length==0) return true;
		String dayMonth = weekday.format(current);
		for (String token:tokens) {
			StringTokenizer st = new StringTokenizer(token,",");
			boolean or = false;
			while (st.hasMoreTokens()) {
				String cond = st.nextToken().trim();
				if (cond.contains(":") && cond.contains("-")) {
					c.setTime(current);
					int min = c.get(Calendar.MINUTE)+c.get(Calendar.HOUR_OF_DAY)*60;
					// time
					String[] parts = cond.split("-");
					if (parts.length==2) {
						int start = getMinuteOfDay(parts[0]);
						int end = getMinuteOfDay(parts[1]);
						if (min>=start && min<end) {
							or=true;
							break;
						}
					}
					else
						throw new RuntimeException("Wrong numberformant for Time "+Arrays.toString(tokens));
				}
				else if (dayMonth.toLowerCase().contains("-"+cond.toLowerCase()+"-")){
					or=true;
					break;
				}
			}
			if (or==false) return false;
		}
		return true;
	}
	
	private int getInt(String s) {
		if (s.length()==0) return 0;
		while (s.startsWith("0") && s.length()>1) s=s.substring(1);  
		return Integer.parseInt(s);
	}
	
	private int getMinuteOfDay(String p) {
		if (p==null || !p.contains(":")) throw new RuntimeException("Wrong numberformant for Time "+Arrays.toString(tokens));
		p = p.trim();
		int s=p.indexOf(":");
		return  getInt(p.substring(0,s)) * 60 +  getInt(p.substring(s+1));
	}

	public String getPrefix() {
		return (prefix==null || prefix.length()==0)?"":(prefix+".");
	}
	
	public String getId() {
		return prefix;
	}

	public String getDescr() {
		if (prefix==null || prefix.length()==0) return System.getProperty("descr.times.default", "Standard");
		return  System.getProperty("descr.times."+prefix,prefix);
	}

}
